package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.common.exception.CustomException;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.threadlocal.WmThreadLocalUtils;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {
    @Autowired
    FileStorageService fileStorageService;
    @Autowired
    WmMaterialMapper wmMaterialMapper;

    @Value("${file.oss.web-site}")
    String webSite;

    @Value("${file.oss.profix}")
    String profix;
//上传图片
    @Override
    public ResponseResult uploadPicture(MultipartFile file) {
        if (file.isEmpty()) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //文件上传0ss


        try {
            String originalFilename = file.getOriginalFilename();
            String uuidName = UUID.randomUUID().toString().replace("-", "");
            String postFix = originalFilename.substring(originalFilename.lastIndexOf("."));
            String newFileName = uuidName + postFix;
            String fileId = fileStorageService.store(profix, newFileName, file.getInputStream());

            if (StringUtils.isBlank(fileId)) {
                CustException.cust(AppHttpCodeEnum.FILE_UPLOAD_ERROR);
            }

            //3.封装Wmmaterial 保存到数据库
            WmMaterial wmMaterial = new WmMaterial();
            wmMaterial.setUrl(fileId);
            wmMaterial.setType((short) 0);
            wmMaterial.setIsCollection((short) 0);
            wmMaterial.setCreatedTime(new Date());


            WmUser user = WmThreadLocalUtils.getUser();
            wmMaterial.setUserId(user.getId());
            save(wmMaterial);


            wmMaterial.setUrl(webSite + fileId);


            return ResponseResult.okResult(wmMaterial);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("file upload oss error:{}", e);
        }

        return ResponseResult.errorResult(AppHttpCodeEnum.FILE_UPLOAD_ERROR);
    }

    @Override
    public ResponseResult findList(WmMaterialDto dto) {
        dto.checkParam();
        LambdaQueryWrapper<WmMaterial> wrapper = new LambdaQueryWrapper<>();

        if (dto.getIsCollection() != null && dto.getIsCollection() == 1) {
            wrapper.eq(WmMaterial::getIsCollection, dto.getIsCollection());
        }

        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            throw new CustomException(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        }
        wrapper.eq(WmMaterial::getUserId, user.getId());
        //创建倒叙
        wrapper.orderByDesc(WmMaterial::getCreatedTime);

        Page<WmMaterial> page = new Page<>(dto.getPage(), dto.getSize());
        IPage<WmMaterial> pageResult = page(page, wrapper);
        //处理图片 拼接
        List<WmMaterial> wmMaterials = pageResult.getRecords();
        for (WmMaterial wmMaterial : wmMaterials) {
            wmMaterial.setUrl(webSite + wmMaterial.getUrl());
        }
        return new PageResponseResult(dto.getPage(), dto.getSize(),
                (int) pageResult.getTotal(), pageResult.getRecords());
    }

    @Override
    public ResponseResult delPicture(Integer id) {
        if (id == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmMaterial wmMaterial = getById(id);
        if (wmMaterial == null) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        LambdaQueryWrapper<WmMaterial> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WmMaterial::getUserId,id);
        Integer count = wmMaterialMapper.selectCount(wrapper);
        if (count>0){
            throw new CustomException(AppHttpCodeEnum.FILE_DELETE_ERROR);
        }
        //删除图片
        fileStorageService.delete(wmMaterial.getUrl());
        //删除素材
        removeById(id);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult updateStatus(Integer id, Short type) {
        if (id==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        Integer uid = WmThreadLocalUtils.getUser().getId();
        update(Wrappers.<WmMaterial>lambdaUpdate()
                .set(WmMaterial::getIsCollection,type)
                .eq(WmMaterial::getId,id)
                .eq(WmMaterial::getUserId,uid)
        );
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
